import {
Api
} from 'api.js'
import {
Config
} from 'config.js'
const config = new Config();
const api = new Api();
class Common{
    constructor() {

    }

    /**
     * 检查会员登录态
     */
    checkLogin = function () {
      let token = this.getToken();
      if (!token) {
        api.pathTo('/pages/login/login', 'nav');
        return false;
      }
      return true;
    }

    /**
     * 检查会员登录态和经销商状态
     */
    checkStatus = function(){
      let token = this.getToken();

      if (!this.checkLogin()) {
        return false;
      }

      let membership = wx.getStorageSync('membership');
      if (!membership) {
        api.pathTo('/pages/login/login', 'nav');
        return false;
      }

      if (membership.distributorCertificationStatus == 0) {

        let checked = this.checkAgentDistributorCertificationStatus(membership);

        if (checked) return true;

        wx.showToast({
          title: '您还未认证'
        })
        return false;
      } else {
        return true;
      }
    }

    /**
     * 检查经商商状态
     */
    checkCertificationStatus = function () {
      let token = this.getToken();

      if (!token) {
        return false;
      }

      let membership = wx.getStorageSync('membership');

      if (!membership) {

        return false;

      }
      if (membership.distributorCertificationStatus == 0) {

        return this.checkAgentDistributorCertificationStatus(membership);

      } else {

        return true;

      }
    }
    /**
     * 检查代理经销商的认证状态
     */
  checkAgentDistributorCertificationStatus = function (membership){
      //如果开启代理模式
      if (membership.agentDealer == 1) {
        let distributor = membership.distributor;
        if (distributor) {
          if (distributor.distributorCertificationStatus > 0) {
            return true;
          }
        }
      }
      return false;
    }

    /**
     * 加载会员信息保存在本地库中
     */
    loadMembershipToStorage = function () { 
      let token = this.getToken();
      api.request({
        access_token: token,
      }, `${config.resourceUrl}membership/find-membership`)
        .then(res => {
          let membership = res.data.data;
          let app = getApp();
          if (!membership) {
            app.globalData.hasChecked = false;
          }else if (membership.distributorCertificationStatus == 0) {
            app.globalData.hasChecked = this.checkAgentDistributorCertificationStatus(membership);
          } else {
            app.globalData.hasChecked = true;
          }
          api.setStorage('membership', res.data.data);
        });
    }
    /**
     * 分享转发
     */
    shareAppMessage = function (ops) {

      let path = '/pages/start/start';
      let params = ''
      if(ops){
        if (ops.path) path = ops.path;
        if (ops.params) params = ops.params;
      }

      let setParam = function(key,value){
        if (params.indexOf('?') == -1) {
          params = '?' + key + '=' + value;
        } else {
          params += '&' + key + '=' + value;
        }
      }

      let brand = wx.getStorageSync('brand');
      if (brand) {
        setParam('brand', brand);
      }

      let membership = wx.getStorageSync('membership');
      if (membership) {
        if (!params){
          //如果开启代理模式,用所属经销商的品牌
          if (membership.distributorCertificationStatus == 0 && membership.agentDealer == 1) {
            let distributor = membership.distributor;
            if (distributor) {
              if (distributor.distributorCertificationStatus > 0) {
                setParam('brand', distributor.brand);
              }
            }
          }else if(membership.brand){
            setParam('brand', membership.brand);
          }
        }
        setParam('sharePhoneNumber', membership.telephone);
      }else{
        let phoneNumber = wx.getStorageSync('phoneNumber');
        if (phoneNumber){
          setParam('sharePhoneNumber', phoneNumber);
        }
      }
      console.log(path + params);
      return {
        title: '尚朴软装',
        path: path + params,
        desc: path + params,
        success: function (res) {
          // 转发成功
          //console.log("转发成功:" + JSON.stringify(res));
        },
        fail: function (res) {
          // 转发失败
          //console.log("转发失败:" + JSON.stringify(res));
        }
      }
    }

  /**
   * 解析分享转发参数
   */
  parseShareOps = function (ops) {
    if (ops.brand) {
      wx.setStorageSync('brand', ops.brand);
    }
    if (ops.sharePhoneNumber) {
      wx.setStorageSync('sharePhoneNumber', ops.sharePhoneNumber);
    }
  }
  /**
  * 请求字典缓存
  */
  loadDictionaryToStorage = function(){

    api.request({}, `${config.resourceUrl}dictionary/dictionary-all`)
      .then(res => {
        let dictionary = {};
        // 设置字典缓存
        for (let i = 0; i < res.data.data.length; i++) {
          let item = res.data.data[i];
          if (!dictionary[item.dictionaryType.dataCode])
            dictionary[item.dictionaryType.dataCode] = [];
          dictionary[item.dictionaryType.dataCode].push(item);
        }
        return api.setStorage('dictionary', dictionary);
      });
  }

  /**
 * 获取token令牌
 */
  getToken() {

    let token = wx.getStorageSync('token');
    let expireTime = token.expireTime;
    //当前时间
    let timestamp = Date.parse(new Date());

    //如果token过期，就重新登录
    if (timestamp > expireTime) {
      api.pathTo('/pages/login/login');
      return;
    }else
    //如果token在3个小时内要过期，就刷新token
    if (timestamp > expireTime-3*60*60*1000) {

      api.request({
        grant_type: 'refresh_token',
        client_id: config.client_id,
        client_secret: config.client_secret,
        refresh_token: token.refresh_token
      }, `${config.authUrl}oauth/token`, 'POST')
        .then(res => {
          /**
           * 计算过期时间
           */
          //当前时间
          let timestamp = Date.parse(new Date());
          //计算过期时间
          res.data.expireTime = timestamp + res.data.expires_in * 1000;
          api.setStorage('token', res.data);
        });
    }
    return token.access_token;
  }

  /**
   * 获取客服来源
   */
  getCustomerServiceSource() {
    let userInfo = wx.getStorageSync('userInfo');
    let membership = wx.getStorageSync('membership');

    let getSource = function (member) {
      return (member && member.membershipLevel && member.brand 
      ? (member.brand + member.membershipLevel.level.toUpperCase()): 'default');
    }
    
    let source = getSource(membership);

    //如果开启代理模式，用所属经销商的来源
    if (membership.distributorCertificationStatus==0 && membership.agentDealer == 1) {
      let distributor = membership.distributor;
      if (distributor) {
        if (distributor.distributorCertificationStatus > 0) {
          source = getSource(distributor);
        }
      }
    }


    return {
      userInfo: userInfo,
      membership: membership,
      //客服来源，来源由品牌+级别组成
      '7moor': source
    }
  }

  /**
  * 登记用户访问记录
  */
  visitRecord = function () {
    let data = {};

    let userLocation = wx.getStorageSync('userLocation');
    if (userLocation){
      data.code = userLocation.adcode;
    }

    let token = this.getToken();
    if(token){
      data.access_token = token;
    }

    let brand = wx.getStorageSync('brand');
    if (brand) {
      data.brand = brand;
    }

    let systemInfo = wx.getSystemInfoSync();
    data.terminalEquipment = systemInfo.system + '|' + systemInfo.brand + ' ' + systemInfo.model;
    data.platform = systemInfo.platform
    
    let openid = wx.getStorageSync('openid');

    api.request(data, `${config.resourceUrl}visitor-visit-records/mnp/${openid}`,'POST')
      .then(res => {
        if (res.data.code==0)
          wx.setStorageSync('visitor-visit-records',res.data.data);
      });
  }



}


export { Common };